import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  message,
  Row,
  Select,
  Space,
  Spin,
} from 'antd';
import React, {
  Fragment,
  useContext,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { MyEditor } from '@/components/MyEditor';
import pageStyles from '@/common/pageLayout.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import {
  addAnnounceService,
  editAnnounceService,
  getLoadMapUpdate,
} from '../service';
import { AnnounceUpdateContext } from '../common/UpdateContext';
import {
  getCompanyID,
  getCompanyName,
  getKeyRouter,
  getPosIDs,
  getTenantID,
  getUserDepID,
  getUserDepName,
  getUserID,
} from '@/utils';
import moment from 'moment';
import { AnnounceManageAPI } from '../common/type';
const { RangePicker }: any = DatePicker;
import { PlusCircleOutlined } from '@ant-design/icons';
import { ReceiveDeptModal } from './ReceiveDeptModal';
import { UploadFormCommon } from '@/components/UploadForm';
import { history } from 'umi';
import { IActionEnum } from '../common/UpdateReducer';

/**
 * 公告新增编辑页面左侧布局
 * @returns
 */
const UpdateViewLeft: React.FC<AnnounceManageAPI.IUpdateViewLeft> = ({
  getAnnounceLoading,
}) => {
  const [updateForm] = Form.useForm();

  const {
    curRes,
    dispatch,
    prefixCls,
    leftSelectRows,
    announceInfo,
    leftSelectKeys,
    locationProps,
    reloadAnnounceInfo,
  } = useContext(AnnounceUpdateContext);

  /**
   * 获取数据字典
   */
  const { mapDataList, mapLoading } = getLoadMapUpdate(curRes);

  /**
   * 控制是否显示 接收部门按钮
   */
  const [showReceive, setShowReceive] = useState<boolean>(false);

  /**
   * 是否显示 接收部门弹框
   */
  const [showReceiveModal, setShowReceiveModal] = useState<boolean>(false);

  useEffect(() => {
    if (announceInfo && announceInfo?.id && locationProps?.state?.id) {
      let receiveList: any[] = announceInfo?.id
        ? announceInfo?.receiveDeptIds?.split(',')
        : [];
      updateForm?.setFieldsValue({
        ...announceInfo,
        announceTime: [
          moment(announceInfo?.startTime),
          moment(announceInfo?.endTime),
        ],
        receiveDeptIds:
          announceInfo?.viewRange == 1
            ? getUserDepName()
            : `已选择${receiveList?.length}个部门`,
        attachUrl: announceInfo?.attachUrl,
        announceContent: announceInfo?.announceContent?.contentHtml,
      });

      if (announceInfo?.viewRange == 0) {
        editHandleDept();
        // setShowReceive(true)
      }
    }
  }, [locationProps, announceInfo]);

  /**
   * 处理编辑默认选中部门
   */
  const editHandleDept = () => {
    let receiveList: any[] = announceInfo?.id
      ? announceInfo?.receiveDeptIds?.split(',')
      : [];
    dispatch({
      type: IActionEnum.LEFTSELECT_KEYS,
      payload: receiveList,
    });
  };

  useEffect(() => {
    if (showReceive) {
      updateForm?.setFieldsValue({ receiveDeptIds: getUserDepName() });
    } else {
      if (leftSelectRows && leftSelectRows?.length > 0) {
        updateForm?.setFieldsValue({
          receiveDeptIds: `已选择${leftSelectRows?.length}个部门`,
        });
      } else {
        updateForm?.setFieldsValue({ receiveDeptIds: undefined });
      }
    }
  }, [showReceive, leftSelectRows]);

  /**
   * 新增编辑回调
   * @param res 接口返回数据
   * @param callType true 为新增回调  || false 为编辑回调
   */
  const updateAnnounceCallback = (res: any, callType: boolean) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      if (callType) {
        history.push({
          pathname: `/announceController/edit/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            id: res?.obj?.id,
            delRouterName: history.location.pathname, //必传,要删除的路由名称
          },
        });
      } else {
        reloadAnnounceInfo();
      }
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入新增
   */
  const { addAnnounceLoading, addAnnounceRun } = addAnnounceService(
    updateAnnounceCallback,
  );
  /**
   * 引入编辑
   */
  const { editAnnounceLoading, editAnnounceRun } = editAnnounceService(
    updateAnnounceCallback,
  );

  /**
   * 处理选中的接收部门
   */
  const receiveListMemo = (rangType: number) => {
    let dataList: any[] = [];
    if (rangType == 0) {
      leftSelectRows?.forEach((item: any) => {
        if (item?.id) {
          let obj: any = {
            receiveDepartmentID: item?.id,
            receiveDepartmentName: item?.text,
            receiveCompanyID: item?.attributes?.companyID
              ? item?.attributes?.companyID
              : null,
            receiveCompanyName: item?.attributes?.companyName
              ? item?.attributes?.companyName
              : null,
          };
          dataList?.push(obj);
        }
      });
    }
    if (rangType == 1) {
      let obj: any = {
        receiveDepartmentID: getUserDepID(),
        receiveDepartmentName: getUserDepName(),
        receiveCompanyID: getCompanyID(),
        receiveCompanyName: getCompanyName(),
      };
      dataList?.push(obj);
    }
    return dataList;
  };

  /**
   * 保存公告
   * @param saveType 判断是保存还是直接签发  Save 保存 || Issued 直接签发
   */
  const saveAnnounce = (saveType: string) => {
    updateForm?.validateFields()?.then((values: any) => {
      let [startTime, endTime]: any = values?.announceTime;
      let time = {
        startTime: startTime.format('YYYY-MM-DD 00:00:00'),
        endTime: endTime.format('YYYY-MM-DD 23:59:59'),
      };

      let announceObj = {
        contentHtml: values?.announceContent?.contentHtml,
        contentText: values?.announceContent?.contentText,
      };

      if (announceInfo && announceInfo?.id) {
        let updatePayload: any = {
          ...values,
          ...time,
          receiveDeptIds:
            values?.viewRange == 1
              ? getUserDepID()
              : leftSelectKeys?.toString(),
          id: announceInfo?.id,
          versionNum: announceInfo?.versionNum,
          state: announceInfo?.state,
          receiveList: receiveListMemo(values?.viewRange),
          announceContent: announceObj,
        };
        delete updatePayload['announceTime'];
        if (saveType == 'Issued') {
          updatePayload['signType'] = 0;
          updatePayload['signerID'] = getUserID();
          updatePayload['signPositionID'] = getPosIDs();
          updatePayload['signDepartmentID'] = getUserDepID();
          updatePayload['signCompanyID'] = getCompanyID();
        }
        editAnnounceRun(updatePayload);
      } else {
        let updatePayload: any = {
          ...values,
          ...time,
          receiveDeptIds:
            values?.viewRange == 1
              ? getUserDepID()
              : leftSelectKeys?.toString(),
          state: `${getTenantID()}12021000`,
          isTop: 0,
          signType: 1,
          receiveList: receiveListMemo(values?.viewRange),
          announceContent: announceObj,
        };
        delete updatePayload['announceTime'];
        if (saveType == 'Issued') {
          updatePayload['signType'] = 0;
          updatePayload['signerID'] = getUserID();
          updatePayload['signPositionID'] = getPosIDs();
          updatePayload['signDepartmentID'] = getUserDepID();
          updatePayload['signCompanyID'] = getCompanyID();
        }
        addAnnounceRun(updatePayload);
      }
    });
  };

  /**
   * 删除文件方法
   * @param delUrl 删除url
   * @param attachmentPath 附件路径
   */
  const delFileCall = (delfilePath: string, attachmentPath: any) => {};

  /**
   * 处理是否展示操作按钮框
   */
  const handleOperation = useMemo(() => {
    let isShowBtn: any = {
      allBtnDiv: false,
      issuedBtn: false,
      saveBtn: false,
    };
    if (
      curRes?.['/announceController/sign'] &&
      (announceInfo && announceInfo?.id
        ? announceInfo?.state == `${getTenantID()}12021000` ||
          announceInfo?.state == `${getTenantID()}12021003`
        : true)
    ) {
      isShowBtn['issuedBtn'] = true;
      isShowBtn['allBtnDiv'] = true;
    }

    if (
      announceInfo && announceInfo?.id
        ? announceInfo?.state == `${getTenantID()}12021000` ||
          announceInfo?.state == `${getTenantID()}12021003`
        : true
    ) {
      isShowBtn['saveBtn'] = true;
      isShowBtn['allBtnDiv'] = true;
    }

    return isShowBtn;
  }, [curRes, announceInfo]);

  return (
    <Fragment>
      <Card
        title={announceInfo && announceInfo?.id ? '编辑公告' : '新增公告'}
        className={pageStyles['page-view']}
        bodyStyle={{ height: '90%', padding: '12px 0px 0px' }}
      >
        <Spin
          spinning={
            getAnnounceLoading || addAnnounceLoading || editAnnounceLoading
          }
        >
          <Row className={'cardBodyRow'}>
            <Col span={24} className={'cardBodyCol'}>
              <ScrollBarLayout>
                <div
                  className={pageStyles['fromView-stylesPage']}
                  style={{ padding: '5px 48px 5px 0px' }}
                >
                  <Form form={updateForm}>
                    <Row>
                      <Col span={24}>
                        <Form.Item
                          label={'公告标题'}
                          name="announceTitle"
                          rules={[
                            {
                              required: true,
                              message: '请输入公告标题',
                            },
                          ]}
                        >
                          <Input placeholder="请输入公告标题" allowClear />
                        </Form.Item>
                      </Col>
                      {/* <Col span={12}>
                            <Form.Item
                              label={'是否置顶'}
                              name="isTop"
                              initialValue={0}
                              rules={[
                                {
                                  required: true,
                                  message: '请选择是否置顶',
                                },
                              ]}
                            >
                              <Select placeholder="请选择是否置顶" allowClear>
                                <Select.Option key={0} value={0}>
                                  否
                                </Select.Option>
                                <Select.Option key={1} value={1}>
                                  是
                                </Select.Option>
                              </Select>
                            </Form.Item>
                          </Col> */}
                      <Col span={12}>
                        <Form.Item
                          label="公告类别"
                          name="announceType"
                          rules={[
                            {
                              required: true,
                              message: '请选择公告类别',
                            },
                          ]}
                        >
                          <Select
                            placeholder="请选择公告类别"
                            allowClear
                            loading={mapLoading}
                          >
                            {mapDataList?.[`${getTenantID()}1201`]?.map(
                              (item: any) => {
                                return (
                                  <Select.Option
                                    key={item?.id}
                                    value={item?.id}
                                  >
                                    {item?.name}
                                  </Select.Option>
                                );
                              },
                            )}
                          </Select>
                        </Form.Item>
                      </Col>
                      {/* <Col span={12}>
                            <Form.Item
                              label="公告状态"
                              name="state"
                              rules={[
                                {
                                  required: true,
                                  message: '请选择公告状态',
                                },
                              ]}
                              // initialValue={`${getTenantID()}12021000`}
                              initialValue={`起草`}
                            >
                              <Input disabled />
                            </Form.Item>
                          </Col> */}
                      <Col span={12}>
                        <Form.Item
                          label="公示时间"
                          name="announceTime"
                          rules={[
                            {
                              required: true,
                              message: '请选择公示时间',
                            },
                          ]}
                        >
                          <RangePicker
                            style={{ width: '100%' }}
                            format="YYYY-MM-DD"
                            placeholder={['开始日期', '结束日期']}
                            ranges={{
                              今天: [moment(), moment()],
                              本周: [
                                moment().startOf('week'),
                                moment().endOf('week'),
                              ],
                              本月: [
                                moment().startOf('month'),
                                moment().endOf('month'),
                              ],
                              本年: [
                                moment().startOf('year'),
                                moment().endOf('year'),
                              ],
                            }}
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label={'可见范围'}
                          name="viewRange"
                          initialValue={0}
                          rules={[
                            {
                              required: true,
                              message: '请选择可见范围',
                            },
                          ]}
                        >
                          <Select
                            placeholder="请选择可见范围"
                            allowClear
                            onChange={(selectKey: string) => {
                              if (selectKey == '0') {
                                setShowReceive(false);
                              } else if (selectKey == '1') {
                                setShowReceive(true);
                              }
                            }}
                          >
                            <Select.Option key={0} value={0}>
                              公司
                            </Select.Option>
                            <Select.Option key={1} value={1}>
                              部门
                            </Select.Option>
                          </Select>
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label={'接收部门'}
                          name="receiveDeptIds"
                          rules={[
                            {
                              required: true,
                              message: '请选择接收部门',
                            },
                          ]}
                        >
                          <Input
                            disabled={true}
                            placeholder="请选择接收部门"
                            addonAfter={
                              showReceive ? (
                                false
                              ) : (
                                <a
                                  onClick={() => {
                                    setShowReceiveModal(true);
                                  }}
                                >
                                  <PlusCircleOutlined />
                                </a>
                              )
                            }
                          />
                        </Form.Item>
                      </Col>
                      <UploadFormCommon
                        form={updateForm}
                        fileFormName={'attachUrl'}
                        spanCol={24}
                        inRowProportion={6}
                        name={'attachFile'}
                        label="相关附件"
                        required={false}
                        accept={'.jpg|.png|.jpeg|.doc|.docx'}
                        url={'/announceController/uploadFile'}
                        downloadUrl={'/announceController/downloadFile'}
                        fileFormDelName={'delLicenceUrl'}
                        delFunc={() => {}}
                        maxFile={5}
                        defaultFiles={
                          announceInfo && announceInfo?.id
                            ? announceInfo?.attachUrl
                            : null
                        }
                      >
                        上传附件
                      </UploadFormCommon>
                    </Row>
                    <Row>
                      <Col span={24}>
                        <Form.Item
                          label="公告内容"
                          name="announceContent"
                          rules={[
                            {
                              required: true,
                              message: '请输入公告内容',
                            },
                          ]}
                        >
                          <MyEditor
                            bodyHeight={450}
                            editorForm={updateForm}
                            formName={'announceContent'}
                            editorValue={
                              announceInfo && announceInfo?.id
                                ? announceInfo?.announceContent?.contentHtml
                                : ''
                            }
                          />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Form>
                </div>
              </ScrollBarLayout>
              {handleOperation?.allBtnDiv && (
                <div className={'cardBodybtn'}>
                  <Space>
                    {handleOperation?.saveBtn && (
                      <Button
                        type={'primary'}
                        onClick={() => {
                          saveAnnounce('Save');
                        }}
                      >
                        保存
                      </Button>
                    )}
                    {handleOperation?.issuedBtn && (
                      <Button
                        type={'primary'}
                        onClick={() => {
                          saveAnnounce('Issued');
                        }}
                      >
                        直接签发
                      </Button>
                    )}
                  </Space>
                </div>
              )}
            </Col>
          </Row>
        </Spin>
      </Card>

      {showReceiveModal && (
        <ReceiveDeptModal
          onClose={() => {
            // dispatch({
            //   type: IActionEnum.CLEAR_RECEIVE
            // })
            setShowReceiveModal(false);
          }}
        />
      )}
    </Fragment>
  );
};

export { UpdateViewLeft };
